package com.sup.servlet;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sup.entity.Category;
import com.sup.entity.Project;

/**
 * Servlet implementation class ShowCategoryServlet
 */
@WebServlet("/showCategory")
public class ShowCategoryServlet extends HttpServlet {
	private static EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowCategoryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		this.emf = Persistence.createEntityManagerFactory("PersistenceUnit");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = this.emf.createEntityManager();
		
		Query listCategory = em.createQuery("SELECT Category from Category category");
		List<Category> categories = listCategory.getResultList();
		request.setAttribute("categories", categories);
		
		if(request.getParameter("id") != null){		
			String idCategory = request.getParameter("id");
			Query listProject = em.createQuery("SELECT project FROM Project project WHERE idCategory ="+idCategory);
			List<Project> projects = listProject.getResultList();
			request.setAttribute("projects", projects);
		}
		else
		{
			Query listProject = em.createQuery("SELECT project FROM Project project");
			request.setAttribute("projects", null);
		}
		
		request.getRequestDispatcher("/showCategory.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
